<template>
  <div class="role">
    <!-- 上方搜索框 -->
    <el-form :inline="true" :model="search" class="demo-form-inline">
      <el-form-item label="角色名称：">
        <el-input v-model="search.rname" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchGo()">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh()" plain>重置</el-button>
      </el-form-item>
      <div>
        <el-button v-if="auths.roleadd!=null" type="primary" icon="el-icon-plus" @click="dialogVisible_role = true">添加角色</el-button>
        <el-button v-if="auths.roledelete!=null" type="primary" icon="el-icon-delete" :disabled="deleteButton" @click="deleteRoleByIds()">批量删除
        </el-button>
      </div>
    </el-form>

    <!-- 添加角色-->
    <el-dialog v-if="auths.roleadd!=null" title="添加角色" :visible.sync="dialogVisible_role" width="30%">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="角色名" prop="rname">
          <el-input v-model="form.rname" placeholder="请输入角色名"></el-input>
        </el-form-item>

        <el-form-item label="权限管理" prop="aid">
          <!--          el-tree定义树形结构，管理权限-->
          <!--      default-expanded-keys和default-checked-keys设置默认展开和默认选中的节点。    -->
          <!--      需要注意的是，此时必须设置node-key，其值为节点数据中的一个字段名，该字段在整棵树中是唯一的。-->
          <el-tree
            :data="data"
            show-checkbox
            node-key="aid"
            :default-expanded-keys="[]"
            :default-checked-keys="[]"
            ref="addtree"
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_role = false">取 消</el-button>
        <el-button type="primary" @click="addNewRoleInfo();dialogVisible_role = false;"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 正文列表 -->
    <el-table :data="tableData" @selection-change="selectionChange()" @select="selectRow" @select-all="selectAll"
              style="width: 100%"
    >
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column prop="rid" label="角色id" width="180"></el-table-column>
      <el-table-column prop="rname" label="角色名"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="300"></el-table-column>
      <el-table-column prop="gmtModified" label="修改时间" width="300"></el-table-column>
      <el-table-column prop="handle" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" :title="updateRole"
                     @click="dialogVisible_revise = true;responesChange(scope.row)"
          ></el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" :title="deleteRole"
                     @click="roleDelete();open(scope.row.rid)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--修改角色-->
    <el-dialog v-if="auths.roleupdate!=null" title="修改" :visible.sync="dialogVisible_revise" width="30%">
      <el-form ref="form" :model="changemessage" label-width="80px" :rules="rules">
        <el-form-item label="角色名" prop="rname">
          <el-input v-model="changemessage.rname" placeholder="请输入角色名"></el-input>
        </el-form-item>

        <el-form-item label="权限管理" prop="aid">
          <!--          el-tree定义树形结构，管理权限-->
          <!--      default-expanded-keys和default-checked-keys设置默认展开和默认选中的节点。    -->
          <!--      需要注意的是，此时必须设置node-key，其值为节点数据中的一个字段名，该字段在整棵树中是唯一的。-->
          <el-tree
            :data="data"
            show-checkbox
            node-key="aid"
            :default-expanded-keys="[100]"
            :default-checked-keys="defaultChecked"
            ref="revisetree"
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible_revise = false">取 消</el-button>
              <el-button type="primary" @click="changeRoleMessage">确 定</el-button>
            </span>
    </el-dialog>

    <!--   分页 页码  -->
    <div class="block" style="margin-top:15px;">
      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryparams.page"
        :page-sizes="[5,10,20,50]"
        :page-size="queryparams.offset"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>

import {
  addNewRoleAuths,
  getRoleList,
  deleteRoleById,
  deleteRoleByIds,
  getRoleByName,
  updateRoleById,
  updateAuthToRole, getRoleAuthByRid
} from '@/api/role'

export default {
  data() {
    return {
      auths: '',
      defaultChecked:[],
      treeData:[],
      //权限管理树形结构内容
      data: [{
        aid: 100, label: '人员管理',
        children: [{
          aid: 17, label: '用户列表'
        }, {
          aid: 16, label: '查找用户'
        }, {
          aid: 15, label: '删除人员'
        }, {
          aid: 18, label: '用户修改'
        },{
          aid:19,label: '添加用户'
        }
        ] },{
        aid:200,label: '项目管理',
        children: [
          {
            aid:20,
            label: '项目列表'
          },
          {
            aid:21,
            label: '查找项目'
          },
          {
            aid:22,
            label: '删除项目'
          },
          {
            aid:23,
            label: '项目修改'
          },
          {
            aid:24,
            label: '添加项目'
          }
        ]
      },{
        aid:400,label: '团队管理',
        children: [
          {
            aid:25,
            label: '团队列表'
          },
          {
            aid:26,
            label: '查找团队'
          },
          {
            aid:27,
            label: '删除团队'
          },
          {
            aid:28,
            label: '团队修改',
          },
          {
            aid:29,
            label: '添加团队'
          }
        ]
      }, {
        aid:600, label: '角色管理',
        children: [
          {
            aid:30,
            label: '角色列表'
          },
          {
            aid:31,
            label: '查找角色'
          },
          {
            aid:32,
            label: '删除角色'
          },
          {
            aid:33,
            label: '角色修改'
          },
          {
            aid:34,
            label: '添加角色'
          }
        ]
      }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      updateRole: '修改角色信息',
      deleteRole: '删除角色信息',
      changeVisible: false,
      isClickSelectAll: false,
      searchflag: false,
      search: {
        rname: '',
        page: 1,
        offset: 10
      },
      deleteList: [],
      deleteButton: true,
      queryparams: {
        page: 1,
        offset: 10
      },
      formInline: {
        rid: '',
        rname: '',
        gmt_create: '',
        gmt_modified: '',
        currentPage: 4
      },
      dialogVisible_role: false, //角色添加
      dialogVisible_revise: false, //角色修改
      form: {
        rname: '',
        aid: '',
      },
      rules: {
        rname:
          [{ required: true, message: '请输入角色名', trigger: 'blur' },
            {
              validator: function(rule, value, callback) {
                //校验中英文的正则：/^[\u4e00-\u9fa5_a-zA-Z]+$/
                if (/^[\u4e00-\u9fa5_a-zA-Z]+$/.test(value) == false) {
                  callback(new Error('请输入中文'))
                } else {
                  //校验通过
                  callback()
                }
              }, trigger: 'blur'
            }
          ]
      },
      changemessage: {
        rid: '',
        rname: '',
        aid: ''
      },
      value: '',
      tableData: [],
      total: 0, // 总条数
      NowRid:0
    }
  },
  created() {
    this.getRoleData()
    this.auths = JSON.parse(getAuths())
  },
  methods: {
    handleClose() {
      this.changeVisible = false
    },
    searchGo() {
      this.searchflag = true
      // 先进行参数校验

      // 发送搜索请求
      getRoleByName(this.search).then((res) => {
        if (res.result == 'SUCCESS' && res.code == 200) {
          this.queryparams.page = this.search.page
          this.queryparams.offset = this.search.offset
          this.total = res.data.total
          this.tableData = res.data.data
        }
      })
    },
    refresh() {
      this.search.rid = ''
      this.search.rname = ''
      this.searchflag = false
      this.getRoleData()
    },
    clearForm() {
      this.search.rid = ''
      this.search.rname = ''
    },

    // 批量删除操作
    async deleteRoleByIds() {
      if (this.deleteList.length === 0) {
        this.$alert('请选择需要删除的角色数据', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        return
      }
      const confirmResult = await this.$confirm('此操作将永久删除所选项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message({ message: '已取消删除', center: true })
      }
      deleteRoleByIds(this.deleteList).then(res => {
        this.deleteList = []
        if (res.code !== 200) return this.$message({ message: '删除失败', type: 'error', center: true })

        this.$message({ message: '删除成功', type: 'success', center: true })
        this.getRoleData()
      })
    },
    selectionChange() {
      if (this.deleteList.length == 0) {
        this.deleteButton = true
      }
    },
    // 选中单行数据
    selectRow(selection, row) {
      this.deleteList = []
      for (let i = 0; i < selection.length; i++) {
        this.deleteList.push(selection[i].rid)
      }
      this.deleteButton = false
    },
    // 选中全部数据
    selectAll(selection) {
      this.deleteButton = !this.deleteButton
      console.log('11this.isClickSelectAll', this.isClickSelectAll)
      this.deleteList = []
      for (let i = 0; i < selection.length; i++) {
        this.deleteList.push(selection[i].rid)
      }
    },

    addNewRoleInfo() {
      let auths = []
      this.$refs.addtree.getCheckedNodes(true, false).forEach(item=>{
        auths.push(item.aid)
      })
      // 添加新角色信息
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (auths !== undefined && auths.length > 0) {
            addNewRoleAuths(this.form.rname, auths).then((res) => {
              console.log(res)
              // 这里是回调函数
              if (res.code != 200) return this.changeRoleInfoSuccess('失败', '添加角色失败！')
              this.changeRoleInfoSuccess('成功', '添加角色成功！')
              this.clearForm()
              this.getRoleData()
            })
          } else {
            this.$message.error('请完善表单相关信息！')
            return false
          }
        }
      })
    },

    changeRoleInfoSuccess(title, message) {
      this.$notify({
        title: title,
        message: message,
        type: 'success',
        duration: 2000
      })
    },

    responesChange(role) {  // 响应修改用户按钮
      this.changeVisible = true
      this.changemessage.rid = role.rid
      this.changemessage.rname = role.rname
      this.changemessage.aid = role.aid

      // 缓存当前的rid
      this.NowRid = role.rid

      // 发送请求，获取用户已有的权限
      getRoleAuthByRid(role.rid).then((res)=>{
        let noritems = []
        res.data.forEach(ite=>{
          noritems.push({
            aid:ite
          })
        })
        this.$refs.revisetree.setCheckedNodes(noritems)
      })
    },

    //修改角色数据
    changeRoleMessage() {

      this.$refs.form.validate((valid) => {
        if (valid) {
          updateRoleById(this.changemessage).then((res) => {
            if (res.result = 'SUCCESS' && res.code == 200) {
              // 请求成功
              this.dialogVisible_revise = false
            } else {
              this.dialogVisible_revise = false
            }
          })
        } else {
          this.$message.error('请完善表单相关信息！')
          return false
        }
      })
      let auths = []
      this.$refs.revisetree.getCheckedNodes(true, false).forEach(item=>{
        auths.push(item.aid)
      })
      // 这里需要校验一下数据格式
      this.$refs.form.validate((valid) => {
        if (valid) {
          updateAuthToRole(this.NowRid,auths).then((res) => {
            if (res.result = 'SUCCESS' && res.code == 200) {
              // 请求成功
              this.dialogVisible_revise = false

              this.changeRoleInfoSuccess('提示', '修改角色成功')
            } else {
              this.dialogVisible_revise = false
              this.changeRoleInfoSuccess('提示', res.message)
            }
          })
        } else {
          this.$message.error('请完善表单相关信息！')
          return false
        }
      })

      // 修改用户信息，发送请求
      this.refresh()
      this.clearForm()
      this.getRoleData()

    },

    //获取数据
    getRoleData() {
      let url = '/get/role/info/' + this.queryparams.page + '/' + this.queryparams.offset
      getRoleList(url).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },

    // 删除按钮弹窗及提示
    roleDelete() {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改成功提示
    reviseSuccess() {
      this.$message({
        type: 'success',
        message: '修改成功'
      })
    },
    onSubmit() {
      console.log('submit!')
    },

    //分页设置
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(newSize) {
      this.queryparams.offset = newSize
      // 重新按照pagesize发送请求，请求最新的数据
      if (this.searchflag) {
        this.search.offset = newSize
        this.searchGo()
        return
      }
      this.getRoleData()
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.queryparams.page = val
      if (this.searchflag) {
        this.search.page = val
        this.searchGo()
        return
      }
      this.getRoleData()
    },

    open(role) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 这里发送请求
          let url = 'del/role/by/' + role
          deleteRoleById(url).then(res => {
            if (res.result === 'SUCCESS' && res.code == 200) {
              this.$message({ type: 'success', message: '删除成功!' })
              this.getRoleData() // 重新加载数据
            } else {
              this.$message({ type: 'info', message: '删除失败!' })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }

  }
}
</script>

<style>

.role {
  padding-top: 40px;
  padding-left: 40px;
}
</style>
